Kotlin idioms

Kotlin idioms(科特林惯用语法)

目录:

  1. 创建DTO(POJO/POCO)(Create DTO/POJO/POCO)
  2. 函数参数的默认值(Default values for function parameters)
  3. 过滤列表(Filtering a list)
  4. 字符串插值(String interpolation)
  5. 实例检查(Instance Checks)
  6. 遍历地图(map)/对(key,value)列表
  7. 使用范围(using range)
  8. 只读列表(Read-only list)
  9. 只读地图(Read-only map)
  10. 访问地图(Accessing a map)
  11. 懒惰的属性(lazy property)
  12. 扩展功能(Extension function)
  13. 创建单例对象(Create singleton)
  14. 如果不是null速记
  15. 如果不是null而是速记
  16. 如果为null则执行语句
  17. 获取可能为空的集合的第一项
  18. 如果不为null则执行
  19. 如果不为null,则映射可空值
  20. 在声明时返回
  21. try/catch表达式
  22. if表达式
  23. 返回的方法的Builder样式用法Unit
  24. 单表达式函数
  25. 在对象实例上调用多个方法
  26. Java7尝试使用资源
  27. 方便的通用函数形式,需要通用类型信息
  28. 使用可以为空的布尔值
  29. 交换两个变量

1、Create DTO/POJO/POCO {创建DTO(POJO/POCO)}

描述:类似于JavaBean

/*
使用DTO
*/
fun useCustomBean() {
    //Create data type object with name:James,age:5. 
    val bean = CustomBean("James", 5);
}
/*
主要用于保存数据的类(类似于Java语言的:JavaBean)
自定义数据类型
*/
data class CustomBean(val name: String, val age: Int) {

}

2、Default values for function parameters (函数参数的默认值)

/*
Default values for function parameters
*/
fun foo(name: String = "defaultName", age: Int = 1) {
    print("name:$name,age:$age")
}

3、Filtering a list(过滤列表)

/*
过滤集合
*/
fun filterList() {
    val list = listOf<String>("James", "John", "Jack");

    //过滤James
    val listWithoutJames = list.filter { x -> x == "James" }
}

or ,event shorter:

/*
过滤集合(缩减版/简介版)
*/
fun filterList() {
    val list = listOf<String>("James", "John", "Jack");

    //过滤James
    val listWithoutJames = list.filter { it == "James" }
}

4、String interpolation(字符串插值)

fun stringInterpolation(name: String = "James", age: Int = 10) {

    print("Name:$name,Age:$age");
}

5、Instance Checks(实例/对象检查)

fun instanceCheck(x: Any) {

    val instanceTypeDescription = when (x) {

        is String -> "String";
        is Int -> "Int";
        is Boolean -> "Boolean";
        else -> "Unknown object";
    }
}

6、Traversing a map/list of pairs(遍历Map/List of pairs)

fun traversingMapOrPair() {
    println()
    println()
    val map = mapOf(
        Pair("OneKey", "OneValue"),
        Pair("TwoKey", "TwoValue")
    )

    /*
    print result:

    key:OneKey,value:OneValue
    key:TwoKey,value:TwoValue
    */

    for ((key, value) in map) {
        println("key:$key,value:$value");
    }
}

7、Using range(使用区间/范围)

fun usingRange() {
    for (i in 1..100) {
    }  // closed range: includes 100
    for (i in 1 until 100) {
    } // half-open range: does not include 100
    for (x in 2..10 step 2) {
    }
    for (x in 10 downTo 1) {
    }

    val y = 0;
    if (y in 1..10) {
    }
}

8、Read-only list(只读列表/集合)

fun readOnlyOfList(){
    val list = listOf<String>("c","b","c")
}

9、Read-only map(只读Map/(key,vlaue))

fun readOnlyOfMap() {

    val map = mapOf<String, String>(
        "a" to "A",
        "b" to "B",
        "c" to "C"
    )
}

10、Accessing a map(访问Map)

fun accessingMap(){
    val map = mapOf<String, String>(
        "a" to "A",
        "b" to "B",
        "c" to "C"
    )

    println("""map a =${map["a"]}""")
}

11、Lazy property(懒加载属性)

fun lazyProperty() {
    val lazyVar: String by lazy {
        "Lazy"
    }
    println(lazyVar)
}

12、Extension function (拓展功能)

fun String.extensionSample(input: String): String {
    println()
    println("Input data:$input");
    var outer: String = input;

    outer = outer + " extension";

    println("Out data:$outer");
    return outer;
}

call

"".extensionSample("Hello world");

print result

Input data:Hello world
Out data:Hello world extension

13、Creating a singleton (创建单例对象)

object Singleton{
    var name = "using object to define singleton object"
}

14、If not null shorthand(速记:如果不为null)

fun ifNotNull(){
    val files = File("file");

    //if not null shorthand
    //files is not null,then call function:isFile
    var isFile = files?.isFile;
}

15、If not null and else shorthand(速记:如果不为null,反之..)

fun ifNotNullAndElse() {
    val files = File("file").listFiles();

    //if not null shorthand
    //files is not null,then call function:isFile
    println(files?.size ?: "files is null object");
}

16、Executing a statement if null(如果为null,执行表达式)

fun ifNullExecutingStatement() {
    val values = arrayOf("A", null);

    val email = values[0] ?: throw IllegalStateException("Email is missing!")
}

17、Get first item of a possibly empty collection.(获取可能为null的集合的第一项)

fun getFirstItemOfPossiblyOfCollection() {
    var values = listOf("James", null);

    val value = values.firstOrNull() ?: "";
}

18、Execute if not null(如果不为null,则执行)

fun ifNotNullExecute() {
    println()
    println();
    var values = listOf("James", null);

    values?.let {
        /*
        if values != null
        for loop values.
        */
        for (item in it) {
            print("${item},")
        }
    }
}

19、Map nullable value if not null(如果可为null的map,不为null)

fun ifNotNullMapNullable() {
    println();
    println();

    var values = mapOf<String?, String?>(
        "A" to "1",
        "B" to "2",
        "C" to null
    )

    val value = values?.let {
        //values is not null.
        for ((key, value) in it) {
            print("key:$key -> value:$value")
        }
    } ?: "defaultValue";

    println("$value")
}

20、Return on when statement(when表达式中返回值)

fun transformColor(color: String): Int {

    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid argument!");
    }
}

21、try/catch expression(try/catch表达式)

fun tryCatchExpression() {
    val result = try {
        /*
        Do something
        */
        println("Do something");
        "Do"
    } catch (e: Exception) {
        println(e);
        "Error"
    }

    println(result);//Result = Do or Error.
}

22、if expression(If表达式)

fun ifExpression(parameter:Int){

    val result = if(parameter == 1){
        "1"
    }else if(parameter == 2){
        "2"
    }else{
        "Unknown"
    }

    println(result)
}

23、Builder-style usage of methods that return Unit

fun arrayOfMinusOnes(size: Int): IntArray {

    return IntArray(size).apply { fill(-1) }

}

24、Single-expression function(单个表达式的函数)

fun theAnswer = 42;

This is equivalent to (等价于)

fun theAnswer():Int{
    return 42
}

25、This can be effectively combined with other idioms,leading to short code.(这可以与其他语法一起使用,以缩短代码)

fun transform(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Blue" -> 2
    else -> -1
}

26、Calling multiple methods on an object instance(with) (在对象实例上调用多个函数)

fun multipleMethods() {

    val animal = Animal();

    /*
    使用"with"可以调用多个函数
    */
    with(animal) {
        //调用animal对象的fly
        fly()

        //接着,调用animal对象的run
        run()

        //再接着,调用animal对象的eat
        eat()
    }
}

27、Java7‘s try with resource(Java7的使用资源)

@RequiresApi(Build.VERSION_CODES.O)
fun useResources() {
    val stream = Files.newInputStream(Paths.get("/some/file.txt"))
    stream.buffered().reader().use { reader ->
        println(reader.readText())
    }
}

28、Convenient form for a generic function that requires the generic type information(方便的通用函数形式,需要通用类型信息)

//     ...
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ...

inline fun <reified T : Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)

29、Consuming a nullable Boolean(消耗/使用 可为null的布尔值)

fun useNullableBoolean(b: Boolean?) {

    if (b == true) {
        //b is true
    } else {
        //b is false or null
    }
}

30、Swapping two variables(交换两个变量)

fun swap() {
    var a = 1;
    var b = 1;

    a = b.also {
        b = a
    }
}

   转载规则


《Kotlin idioms》 Air 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录